package com.z.utils.j2e;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.Iterator;

/**
 * @author wenzheng.ma
 * @date 2021-11-27 18:09
 * @desc json to entity 仅String属性，可以扩展其他类型
 */
public class Json2EntityUtils {
    public static Object j2e(String jsonStr, Object dto) throws NoSuchFieldException, IllegalAccessException {
        JSONObject o = JSON.parseObject(jsonStr);
        Iterator<String> it = o.keySet().iterator();
        Field declaredField;
        while (it.hasNext()) {
            String field = it.next();
            declaredField = dto.getClass().getDeclaredField(field);
            declaredField.setAccessible(true);
            declaredField.set(dto, o.get(field));
        }
        return dto;
    }
}
